package com.test.spring.transaction.annoation;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;

/**
 * @author lzy
 * @version v1.0
 * Create DateTime: 2018/9/29 10:07
 */
@Repository("bookShopDao")
public class BookShopDaoImpl implements BookShopDao {

    @Autowired
    private JdbcTemplate jdbcTemplate;

    @Override
    public double findBookPriceByIsbn(String isbn) {
        String sql = "SELECT price FROM Book WHERE isbn=?";
        return jdbcTemplate.queryForObject(sql, Double.class, isbn);
    }

    @Override
    public void updateBookStock(String isbn) {
        //检查书的库存是否足够，若不够，则抛出异常
        String sql1 = "SELECT stock FROM Book WHERE isbn=?";
        int stock = jdbcTemplate.queryForObject(sql1, Integer.class, isbn);
        if (stock <= 0) {
            throw new BookStockException("库存不足");
        }

        String sql2 = "UPDATE Book SET stock=stock-1 WHERE isbn=?";
        jdbcTemplate.update(sql2, isbn);
    }

    @Override
    public void updateUserAccount(String userName, double price) {
        //检查用于余额是否足够，若不够，则抛出异常
        String sql1 = "SELECT balance FROM Account WHERE username=?";
        double balance = jdbcTemplate.queryForObject(sql1, Double.class, userName);
        if (balance < price) {
            throw new UserAccountException("余额不足");
        }

        String sql = "UPDATE Account SET balance=balance-? WHERE username=?";
        jdbcTemplate.update(sql, price, userName);
    }
}
